package com.iiiss.gae.impl.daos;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.iiiss.gae.core.entities.ColumnGae;
import com.iiiss.ssh.core.daos.ColumnDao;
import com.iiiss.ssh.core.entities.Column;
import com.iiiss.ssh.impl.daos.ColumnDaoImpl;

@Repository
public class ColumnDaoGaeImpl extends ColumnDaoImpl implements ColumnDao {

	public Column insert(String name, Column parent) {
		ColumnGae columnGae = (ColumnGae) this.insert(name);
		columnGae.setParent(parent);
		columnGae.setParentId(parent.getId());
		parent.getChildren().add(columnGae);
		return columnGae;
	}

	public Column selectOne(Long id) {
		Column column = super.findEntity(Column.BEAN_NAME, Column.class, id);
		this.restoreParent((ColumnGae) column);
		this.restoreChildren((ColumnGae) column);
		return column;
	}

	public List<Column> selectAll() {
		List<Column> columns = super.findEntities(Column.BEAN_NAME, Column.class);
		for (Column column : columns) {
			this.restoreParent((ColumnGae) column);
			this.restoreChildren((ColumnGae) column);
		}
		return columns;
	}

	private void restoreParent(ColumnGae columnGae) {
		if (columnGae.getParent() != null)
			return;

		Long parentId = columnGae.getParentId();
		if (parentId == null)
			return;

		Column parent = super.findEntity(Column.BEAN_NAME, Column.class, parentId);
		columnGae.setParent(parent);
	}

	private void restoreChildren(ColumnGae columnGae) {
		if (!columnGae.getChildren().isEmpty())
			return;

		List<Column> children = super.findEntities(Column.BEAN_NAME, Column.class,
				"WHERE parentId = ?1", new Object[] { columnGae.getId() });
		columnGae.getChildren().addAll(children);
		for (Column child : children)
			child.setParent(columnGae);
	}

}
